package com.xuan.common.message.service;



import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.google.gson.Gson;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RefreshScope
public class AliSmsService {

    @Resource
    private Client aliSmsClient;

    // 业务配置
    @Value("${sms.signName}")
    private String signName;
    @Value("${sms.templateCode}")
    private String templateCode;


    /**
     *  发送手机短信
     * @param phone
     * @param code
     * @return
     */
    public boolean sendMobileCode(String phone, String code) {
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        return sendTempMessage(phone, signName, templateCode, JSON.toJSONString(params));
    }


    /**
     *  发送模板消息
     * @param phone
     * @param signName
     * @param templateCode
     * @param params
     * @return
     */
    private boolean sendTempMessage(String phone, String signName, String templateCode, String params) {
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName(signName);
        smsRequest.setTemplateCode(templateCode);
        smsRequest.setTemplateParam(params);
        try {
            SendSmsResponseBody smsResponseBody = aliSmsClient.sendSms(smsRequest).getBody();
            if (!"OK".equals(smsResponseBody.getCode())) {
                log.error("短信 {} 发送失败, 失败原因: {}", JSON.toJSONString(smsRequest), smsResponseBody.getMessage());
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("短信 {} 发送失败, 失败原因: {}", JSON.toJSONString(smsRequest), e.getMessage());
            return false;
        }
    }

}
